<template>
  <!-- 待办去处理 的弹出框-->
  <el-dialog
    :title="title"
    :visible.sync="visible"
    append-to-body
    :close-on-click-modal="false"
    @close="close"
    top="5vh"
    width="85%"
    custom-class="todo-handle-dialog"
  >
    <!-- 内容 -->
    <div class="handle-content">
      <div class="title">
        温馨提示：这是评估您近期的心理状态，可能会受到特殊事件和当前心境的影响，此测试结果仅供参考!
      </div>
      <el-collapse v-model="collapseValues">
        <!-- 遍历模块信息 -->
        <el-collapse-item
          v-for="item of infoTypes"
          :key="item['key']"
          :name="item['key']"
        >
          <!-- 标题 -->
          <template slot="title">
            <span class="collapse-title">{{ item["label"] }}</span>
          </template>
          <!-- 内容 -->
          <el-form
            :label-width="'90px'"
            class="info"
            :label-position="'right'"
            size="mini"
          >
            <el-row>
              <el-col
                v-for="col of getColumns(item['key'])"
                :key="col['field']"
                :span="col['span']"
                ><div class="key-item">
                  <el-form-item :label="`${col.label}：`" :prop="col['field']">
                    {{
                      (item["key"] === "userInfo" ? userData : otherData)[
                        col["field"]
                      ]
                    }}
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <!-- 预警信息-特殊处理 -->
        <Warn
          v-if="hdType === 'warn' && warnList && warnList.length"
          ref="refWarn"
          :warnList="warnList"
          :hdEdit="hdEdit"
          :hdRowData="rowData"
        >
        </Warn>
        <!-- 处理意见 -->
        <el-collapse-item name="handleOpinions">
          <!-- 标题 -->
          <template slot="title">
            <span class="collapse-title">处理意见</span>
          </template>
          <!-- 内容 -->
          <el-form
            ref="refSubmitForm"
            :model="submitForm"
            :rules="submitRules"
            :label-position="'right'"
            size="mini"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item prop="handleOpinions">
                  <el-input
                    v-model="submitForm.handleOpinions"
                    type="textarea"
                    size="mini"
                    clearable
                    placeholder="最大支持2000字"
                    maxlength="2000"
                    rows="4"
                    :disabled="!hdEdit"
                  ></el-input>
                  <span
                    style="
                      color: #999;
                      position: absolute;
                      bottom: -25px;
                      right: 0;
                    "
                    >{{ submitForm.handleOpinions.length }}/2000</span
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="hdEdit">
              <el-col :span="24">
                <div class="btns">
                  <el-button
                    round
                    size="small"
                    type="primary"
                    @click.stop="submitOpinions"
                    >提 交</el-button
                  >
                  <!-- <el-button round size="small" @click.stop="saveDraftOpinions">保存草稿</el-button> -->
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
  </el-dialog>
</template>

<script>
import axios from "@/router/axios";
import Warn from "./warn.vue";
import { allInfoTypes, getInfoTypesByType, getColumns, getUrl } from "./config";
export default {
  name: "TodoHandlePop",
  components: { Warn },
  props: {
    // 弹框的title
    title: {
      type: String,
      default: function () {
        return "";
      },
    },
    // 年级列表数据字典
    gradeList: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },
  data() {
    return {
      visible: false,
      hdType: "", // 当前待办类型
      rowData: {}, // 当前处理的数据
      hdEdit: false, // 当前类型是否编辑的状态
      // 默认显示全部折叠面板
      collapseValues: allInfoTypes
        .map((it) => it["key"])
        .concat(["handleOpinions"]),
      userData: {}, // 当前处理的学生信息
      otherData: {}, // 当前处理的其他信息
      baseData: {},
      infoTypes: [],
      // 待提交的表单
      submitForm: {
        handleOpinions: "", // 处理意见
      },
      // 表单校验规则
      submitRules: {
        handleOpinions: [
          { required: true, message: "请输入处理意见", trigger: "blur" },
        ],
      },
      // 接口请求url、请求状态、参数等信息
      apis: {},
      // 预警信息
      warnList: [],
    };
  },
  methods: {
    initApis(handleType, handleRowData) {
      window.axios = axios;
      this.apis = {
        // 提交意见接口
        submit: {
          url: getUrl(handleType, "submit"),
          type: "post", // 接口请求类型
          status: 0, // 接口请求状态，0=未请求，1=请求中
          async getParams(params) {
            if (handleType === "warn") {
              return params;
            }
            let id = handleRowData.id;
            // 参数
            return {
              id: id,
              coachDecs: params.handleOpinions,
            };
          },
        },
        // 报错草稿意见接口
        saveDraft: {
          url: "",
          type: "post", // 接口请求类型
          status: 0, // 接口请求状态，0=未请求，1=请求中
          async getParams(params) {
            // 参数
            return params;
          },
        },
      };
    },
    show(hdType, rowData, isEdit) {
      this.visible = true;
      this.hdType = hdType;
      this.rowData = rowData;
      this.hdEdit = isEdit;
      console.log(hdType, rowData, isEdit);
      this.initCurUserInfo(rowData); // 异步获取/设置学生信息
      this.initApis(hdType, rowData); // 初始化接口设置
      this.initCurOtherInfo(rowData); // 获取/设置当前要处理的预约/预警信息
      this.infoTypes = getInfoTypesByType(hdType);
    },
    close() {
      this.visible = false;
      this.$emit("close");
    },
    // 调用保存类接口 callback 成功的回调
    async callSaveApi(apiOp, params, callback) {
      console.log("callSaveApi", JSON.parse(JSON.stringify(params)));
      if (typeof apiOp["getParams"] === "function") {
        params = await apiOp["getParams"](params);
      }
      apiOp["status"] = 1; // 请求中
      const loading = this.$loading();
      let res = await axios[apiOp["type"]](apiOp["url"], params);
      if (res.status === 200) {
        // 请求成功
        if (typeof callback === "function") {
          callback(params);
        }
      }
      apiOp["status"] = 0; // 恢复未请求状态
      loading.close();
    },
    // 获取/设置当前要处理的学生信息
    async initCurUserInfo(rowData) {
      // 获取用户数据
      this.$store
        .dispatch("GetNewUserInfo", { userId: rowData.userId })
        .then((user) => {
          this.userData = Object.assign({}, user || {}, this.baseData);
        });
    },
    // 获取/设置当前要处理的预约/预警信息
    async initCurOtherInfo(rowData) {
      // 预警
      if (this.hdType === "warn") {
        let { data } = await axios.get(
          `/api/blade-measure/measure/report/findPersonalInfo?id=${rowData.userProjectGaugeId}`
        );

        data = data.data || {};
        this.rowData.gaugeName = data.gaugeName || "";
        this.baseData = {
          gradeName: data.gradeName || ''
        }
        Object.assign(this.userData, this.baseData);
        // 获取预警信息
        this.warnList = data.factorList || [];
        this.submitForm.handleOpinions = data.coachDecs || "";
      }
    },
    // 提交意见
    async submitOpinions() {
      const _this = this;
      this.$refs["refSubmitForm"].validate(async (valid) => {
        if (valid) {
          let params = _this.submitForm;
          // 预警
          if (_this.hdType === "warn") {
            params = await _this.$refs["refWarn"].getData();
            if (!params) {
              return;
            }
            Object.assign(params, {
              coachDecs: _this.submitForm.handleOpinions,
            });
          }
          _this.callSaveApi(_this.apis.submit, params, () => {
            // 成功的回调
            _this.$message({ type: "success", message: "提交成功！" });
            _this.close();
            _this.$emit("submitSuccess", _this); // 触发事件
          });
        }
      });
    },
    // 保存草稿意见
    async saveDraftOpinions() {
      this.callSaveApi(this.apis.saveDraft, this.submitForm, () => {
        // 成功的回调
        this.$message({ type: "success", message: "保存成功！" });
        this.close();
      });
    },
    getColumns,
  },
};
</script>

<style scoped >
/* /deep/.el-form {
  border: 1px solid black;
} */
</style>

<style scoped lang="scss" >
.handle-content {
  .info {
    ::v-deep.el-col {
      // border-top: 1px solid #646566 !important;
      // border-left: 1px solid #646566 !important;
      margin-bottom: 0;
      display: flex;
      align-items: center;

      .key-item {
        display: flex;
        align-items: center;

        .el-form-item {
          margin: 5px 0;
        }
      }
    }

    // ::v-deep.el-col:nth-child(3n) {
    //   border-right: 1px solid #646566;
    // }

    // ::v-deep.el-col:nth-child(n + 4) {
    //   border-bottom: 1px solid #646566;
    // }

    // ::v-deep.el-col:last-child {
    //   width: 100%;
    //   border-top: none !important;
    //   border-right: 1px solid #646566;
    //   padding-right: 1px !important;
    // }
  }
}

.title {
  color: #4994df;
  font-size: 16px;
  padding: 5px 10px;
}

::v-deep .todo-handle-dialog .el-dialog__body {
  height: calc(82vh - 60px);
  overflow-y: auto;
}
::v-deepdeep .el-form-item {
  margin-bottom: 10px;
}
::v-deep .collapse-title {
  font-size: 16px;
  font-weight: 600;
}
.btns {
  margin: 10px 10px 20px;
  text-align: center;
  button {
    margin: 0 10px;
    padding: 10px 40px;
  }
}
::v-deep .el-collapse-item {
  border: 1px solid #ebebeb;
  border-radius: 4px;
  box-shadow: 0 0 8px 0 rgb(232 237 250 / 60%),
    0 2px 4px 0 rgb(232 237 250 / 50%);
  margin-bottom: 10px;
}
::v-deep .el-collapse-item__header {
  padding: 0 10px;
}
::v-deep .el-collapse-item__header.is-active {
  border-bottom: 1px solid #ebebeb;
}
::v-deep .el-collapse-item__content {
  padding: 10px 20px 20px;
}
</style>